import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Card, Form, Input, Cascader, Button, message } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import LinkButton from '../../components/link-button';
import PicturesWall from './pictures-wall';
import RichTextEditor from './rich-text-editor';
import { reqCategorys, reqAddOrUpdateProduct } from '../../api';
import { useLocation, useNavigate } from 'react-router-dom';

const ProductAddUpdate = () => {
  const [form] = Form.useForm();
  const location = useLocation();
  const navigate = useNavigate();
  const [options, setOptions] = useState([]);
  const pw = useRef(null);
  const editor = useRef(null);

  const product = location.state?.product || {};
  const isUpdate = !!product._id;

  useEffect(() => {
    const loadFirstLevelCategories = async () => {
      const result = await reqCategorys('0');
      if (result.status === 0) {
        const firstLevelOptions = result.data.map(c => ({
          value: c._id,
          label: c.name,
          isLeaf: false,
        }));
        if (isUpdate && product.pCategoryId !== '0') {
          const subCategorys = await reqCategorys(product.pCategoryId);
          if (subCategorys.length > 0) {
            const secondLevelOptions = subCategorys.map(c => ({
              value: c._id,
              label: c.name,
              isLeaf: true,
            }));
            const targetOption = firstLevelOptions.find(
              option => option.value === product.pCategoryId
            );
            if (targetOption) {
              targetOption.children = secondLevelOptions;
            }
          }
        }
        setOptions(firstLevelOptions);
      }
    };

    loadFirstLevelCategories();
  }, [isUpdate, product]);

  const loadData = useCallback(async (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    if (targetOption.loading) return;
    targetOption.loading = true;
    try {
      const subCategorys = await reqCategorys(targetOption.value);
      if (subCategorys.length > 0) {
        targetOption.children = subCategorys.map(c => ({
          value: c._id,
          label: c.name,
          isLeaf: true,
        }));
      } else {
        targetOption.isLeaf = true;
      }
    } finally {
      targetOption.loading = false;
      setOptions([...options]);
    }
  }, [options]);

  const validatePrice = (_, value) => {
    if (parseFloat(value) > 0) {
      return Promise.resolve();
    }
    return Promise.reject('价格必须是大于 0 的数值');
  };

  const submit = useCallback(async () => {
    try {
      const values = await form.validateFields();
      const imgs = pw.current?.getImgs() || [];
      const detail = editor.current?.getDetail() || '';

      let pCategoryId, categoryId;
      const [first, second] = values.categoryIds || [];
      if (values.categoryIds.length === 1) {
        pCategoryId = '0';
        categoryId = first;
      } else {
        pCategoryId = first;
        categoryId = second;
      }

      const payload = {
        ...values,
        pCategoryId,
        categoryId,
        detail,
        imgs,
        ...(isUpdate ? { _id: product._id } : {}),
      };

      const result = await reqAddOrUpdateProduct(payload);
      if (result.status === 0) {
        message.success(isUpdate ? '更新商品成功' : '添加商品成功');
        navigate(-1);
      } else {
        message.error(isUpdate ? '更新商品失败' : '添加商品失败');
      }
    } catch (error) {
      console.error('保存商品错误:', error);
      message.error('保存商品时发生错误，请检查网络或重试');
    }
  }, [form, isUpdate, navigate, product]);

  // 如果是更新，则设置初始值
  const initialCategoryIds = () => {
    if (isUpdate) {
      const { pCategoryId, categoryId } = product;
      return pCategoryId === '0' ? [categoryId] : [pCategoryId, categoryId];
    }
    return [];
  };

  return (
    <Card
      title={
        <span>
          <LinkButton onClick={() => navigate(-1)}>
            <ArrowLeftOutlined style={{ fontSize: 20 }} />
          </LinkButton>
          {isUpdate ? '修改商品' : '添加商品'}
        </span>
      }
    >
      <Form form={form} name="productForm" initialValues={{
        name: product.name,
        desc: product.desc,
        price: product.price,
        categoryIds: initialCategoryIds()
      }}>
        <Form.Item name="name" label="商品名称" rules={[{ required: true, message: '请输入商品名称' }]}>
          <Input placeholder="请输入商品名称" />
        </Form.Item>

        <Form.Item name="desc" label="商品描述" rules={[{ required: true, message: '请输入商品描述' }]}>
          <Input.TextArea placeholder="请输入商品描述" autoSize />
        </Form.Item>

        <Form.Item name="price" label="商品价格" rules={[
          { required: true, message: '请输入商品价格' },
          { validator: validatePrice },
        ]}>
          <Input type="number" addonAfter="元" />
        </Form.Item>

        <Form.Item name="categoryIds" label="商品分类" rules={[{ required: true, message: '请选择商品分类' }]}>
          <Cascader options={options} loadData={loadData} />
        </Form.Item>

        <Form.Item label="商品图片">
          <PicturesWall ref={pw} imgs={product.imgs || []} />
        </Form.Item>

        <Form.Item label="商品详情" wrapperCol={{ span: 20 }}>
          <RichTextEditor ref={editor} detail={product.detail || ''} />
        </Form.Item>

        <Button type="primary" onClick={submit} style={{ width: '100%', marginTop: 20 }}>
          {isUpdate ? '保存修改' : '提交添加'}
        </Button>
      </Form>
    </Card>
  );
};

export default ProductAddUpdate;
